# -*- coding: utf-8 -*-
from django.views.generic.simple import direct_to_template
from django.http import HttpResponseRedirect
from django.contrib.auth import login, logout, authenticate


def home(request):
    """
    Site title page
    """
    
    return direct_to_template(request, 'home.html')


def auth(request, **kwargs):
    """
    Login/logout processing
    """
    if 'cmd' in kwargs:
        cmd = kwargs['cmd']
        if cmd == u'login':
            # Try to login
            if not request.user.is_authenticated() \
            and request.method == 'POST' \
            and 'username' in request.POST \
            and 'password' in request.POST:
                user = authenticate(username=request.POST['username'],
                                    password=request.POST['password'])
                if user:
                    login(request, user)
        elif cmd == u'logout':
            # Try to logout
            if request.user.is_authenticated():
                logout(request)
    
    if request.method == 'POST' \
    and 'redirect' in request.POST:
        # Place hidden input, named 'redirect' in login form in html template
        # for making redirect to the same page after login/logout
        return HttpResponseRedirect(request.POST['redirect'])
    
    return HttpResponseRedirect('/')


def i18n(request, **kwargs):
    """
    Change locale processing
    """
    from django.utils.translation import check_for_language
    
    if 'lang' in kwargs:
        lang = kwargs['lang']
        
        if lang and check_for_language(lang):
            if hasattr(request, 'session'):
                request.session['django_language'] = lang
    
    if request.method == 'POST' \
    and 'redirect' in request.POST:
        # Place hidden input, named 'redirect' in login form in html template
        # for making redirect to the same page after login/logout
        return HttpResponseRedirect(request.POST['redirect'])
    
    return HttpResponseRedirect('/')
        